<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-position="top"
           :class="isEdit?'':'formItem'">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">更换轮胎项目明细</span>
      </div>

      <el-row :gutter="24">
        <el-col :span="8" v-if="isShow">
          <el-form-item label="旧轮胎行驶里程:" prop="oldTyreMeligile">
            <el-input v-if="isEdit" v-model="ruleForm.oldTyreMeligile"
                      @change="changeAmount('oldTyreMeligile')"
                      placeholder="输入旧轮胎行驶里程"></el-input>
            <span v-else>{{ ruleForm.oldTyreMeligile }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="是否调换备胎:" prop="isReplaceSpareTire">
            <el-select v-model="ruleForm.isReplaceSpareTire" placeholder="选择是否调换备胎" style="width: 100%;"
                       v-if="isEdit">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="2"></el-option>
            </el-select>
            <span v-else>{{
                ruleForm.isReplaceSpareTire === "1" ? '是' : ruleForm.isReplaceSpareTire ===
                "2" ? '否' : ''
              }}</span>
          </el-form-item>

        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="品牌:" prop="tyreBrand">
            <el-input v-if="isEdit" v-model="ruleForm.tyreBrand" placeholder="输入品牌"></el-input>
            <span v-else>{{ ruleForm.tyreBrand }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8" v-if="isShow">
          <el-form-item label="型号:" prop="tyreModel">
            <el-input v-if="isEdit" v-model="ruleForm.tyreModel" placeholder="输入型号"></el-input>
            <span v-else>{{ ruleForm.tyreModel }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="花纹:" prop="tyreFigure">
            <el-input v-if="isEdit" v-model="ruleForm.tyreFigure"
                      placeholder="输入花纹"></el-input>
            <span v-else>{{ ruleForm.tyreFigure }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="载重指数速度级别:" prop="leadSpeedLevel">
            <el-input v-if="isEdit" v-model="ruleForm.leadSpeedLevel" placeholder="输入载重指数速度级别"></el-input>
            <span v-else>{{ ruleForm.leadSpeedLevel }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8" v-if="isShow">
          <el-form-item label="单价(含税):" prop="unitPrice">
            <el-input v-if="isEdit" v-model="ruleForm.unitPrice"
                      @change="changeAmount('unitPrice')"
                      v-thousand
                      placeholder="输入单价(含税)"></el-input>
            <span v-else>{{ format_thousand(ruleForm.unitPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="轮胎数量(条):" prop="tyreNum">
            <el-input v-if="isEdit" v-model="ruleForm.tyreNum"
                      @change="changeAmount('tyreNum')"
                      placeholder="输入轮胎数量(条)"></el-input>
            <span v-else>{{ ruleForm.tyreNum }}</span>
          </el-form-item>
        </el-col>
<!--        <el-col :span="8" v-if="isShow">-->
<!--          <el-form-item label="合计费用:" prop="totalPrice">-->
<!--            <el-input v-if="isEdit" v-model="ruleForm.totalPrice"-->
<!--                      disabled-->
<!--                      @change="changeAmount('totalPrice')"-->
<!--                      placeholder="输入合计费用(手动输入)"></el-input>-->
<!--            <span v-else>{{ format_thousand(ruleForm.totalPrice) }}</span>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>

      <el-row :gutter="24">
        <el-col v-if="isShow" :span="24">
          <el-form-item label="备注:" prop="tyreRemark">
            <el-input v-if="isEdit" placeholder="输入备注" type="textarea" :rows="4"
            :maxlength="500"  v-model="ruleForm.tyreRemark"></el-input>
            <span v-else>{{ ruleForm.tyreRemark }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col v-if="isShow">
          <el-form-item label="上传附件:" prop="annexUrl">
            <image-common v-model="ruleForm.annexUrl" :limit="20" :disabled="!isEdit" :upType="2"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
</template>

<script>
export default {
  name: "replacementDetails",
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: 'write',
    }
  },
  computed: {
    ruleForm: {
      get() {
        let that = this
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key)
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key)
            }
            that.$emit('input', {...target, [key]: value})
            return true
          }
        })
        return proxy
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
    top() {
      if (this.isEdit) {
        return 'top'
      } else {
        return 'right'
      }
    }
  },
  watch:{
    'value.unitPrice':{
      handler(val){
        if(val){
          this.handleCount()
        }
      },
      immediate:true,
      deep:true
    }
  },
  data() {
    var validateAnnexUrl = (rule, value, callback) => {
      if (this.ruleForm.annexUrl === '' || this.ruleForm.annexUrl === null) {
        callback(new Error('请上传附件'));
      } else {
        callback();
      }
    };
    return {
      isShow: true,
      rules: {
        //更换轮胎项目明细
        oldTyreMeligile: [{required: this.state === 'write', message: '请输入旧轮胎行驶里程', trigger: 'blur'}],
        isReplaceSpareTire: [{required: this.state === 'write', message: '请选择是否调换备胎', trigger: 'change'}],
        tyreBrand: [{required: this.state === 'write', message: '请输入品牌', trigger: 'blur'}],
        tyreModel: [{required: this.state === 'write', message: '请输入型号', trigger: 'blur'}],
        tyreFigure: [{required: this.state === 'write', message: '请输入花纹', trigger: 'blur'}],
        leadSpeedLevel: [{required: this.state === 'write', message: '请输入载重指数速度级别', trigger: 'blur'}],
        unitPrice: [{required: this.state === 'write', message: '请输入单价(含税)', trigger: 'blur'}],
        tyreNum: [{required: this.state === 'write', message: '请输入轮胎数量(条)', trigger: 'blur'}],
        totalPrice: [{required: this.state === 'write', message: '请输入合计费用', trigger: 'blur'}],
        tyreRemark: [{required: this.state === 'write', message: '请输入备注', trigger: 'blur'}],
        annexUrl: [{required: this.state === 'write', validator: validateAnnexUrl, trigger: 'blur'}],
      }
    };
  },

  created() {
    this.handleCount()
  },
  mounted() {
  },
  methods: {
    handleEffect() {

      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            this.locateToErr()
            reject()
          }
        });
      })
    },
    locateToErr() {

      this.$nextTick(() => {
        let isError = document.getElementsByClassName('is-error')
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },
    valid() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      })
    },
    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
      if (str === 'tyreFigure' || str === 'tyreNum') {
        msg = /^[1-9]\d*$/
        if (!msg.test(this.ruleForm[str])) {
          this.ruleForm[str] = ""
        } else {
          this.ruleForm[str] = this.ruleForm[str].toString().match(/^[1-9]\d*$/)[0]
        }
      } else {
        if (!msg.test(this.ruleForm[str])) {
          this.ruleForm[str] = ""
        } else {
          this.ruleForm[str] = this.ruleForm[str].toString().match(/^\d+(?:\.\d{0,2})?/)[0]
        }
      }
    },

    handleCount() {
      let num = this.ruleForm.unitPrice * this.ruleForm.tyreNum || 0
      this.$set(this.value, 'totalPrice', num)
    },
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/styles/cwgd/formScss.scss";
</style>


